import AlipaySdk from "./alipay/alipay";
import AliPayForm from "./alipay/form";
import fs from "fs";
import path from "path";
import { Service } from "typedi";
import { config } from "../config";

@Service()
export class Alipay {
	private alipaySdk: any;
	private formData: any;
	
	constructor () {
		this.alipaySdk = new AlipaySdk({
			appId: config.alipay.appId,
			alipayPublicKey: fs.readFileSync(path.join(__dirname, config.alipay.keyPath.publicKey), 'ascii'),
			privateKey: fs.readFileSync(path.join(__dirname, config.alipay.keyPath.privateKey), 'ascii')
		});
	}
	
	/**
	 * 设置需要提交给支付宝支付的表单参数
	 * @param params
	 */
	public setFormData (params) {
		this.formData = new AliPayForm();
		this.formData.setMethod('get'); // 返回get支付地址，而不是form表单代码
		this.formData.addField('notifyUrl', config.alipay.notifyUrl);
		this.formData.addField('returnUrl', config.alipay.returnUrl);
		
		this.formData.addField('bizContent', {
			outTradeNo: params['outTradeNo'],
			productCode: 'FAST_INSTANT_TRADE_PAY',
			totalAmount: params['totalAmount'],
			subject: config.alipay.subject,
			body: `${params['body']},购买怪客课堂课程`,
			goodsType: '1'
		});
		
	}
	
	public async startPay () {
		return await this.alipaySdk.exec("alipay.trade.page.pay", {},  {
				formData: this.formData
			}
		)
	}
	
}